﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Common;
using Ice.Toolkit.Data.Entity;
using Ice.Toolkit.Data.ILInvoker;


namespace Ice.Toolkit.Data.Sql
{
    internal class SelectBuilder<T> : BuilderBase<T> where T : EntityBase<T>, new()
    {
        private List<Expression<Func<T, bool>>> _where;
        private List<String> _orderBy;
 
        public SelectBuilder(DataContext dataContext, List<Expression<Func<T, bool>>> where, List<string> orderBy, int take, bool isCount = false)
            : base(dataContext)
        {
            _where = where;
            _orderBy = orderBy;

            if (isCount)
            {
                SQLText = "SELECT COUNT(*) FROM {0} ";
            }
            else
            {
                if (take > 0)
                {
                    SQLText = "SELECT TOP " + take + " * FROM {0} ";
                }
                else
                {
                    SQLText = "SELECT * FROM {0} ";
                }
            }
        }

        public override string Build()
        {
            if (_where.Count > 0)
            {
                SQLText += "WHERE (";

                foreach (var item in _where)
                {
                    var sqlWhere = new SqlWhere<T>(item);

                    SQLText += sqlWhere.SqlWhereText + ") AND (";

                    var loop = sqlWhere.Columns.Count;

                    for (var i = 0; i < loop; i++)
                    {
                        AddParameter(sqlWhere.Columns[i], sqlWhere.Values[i]);
                    }
                }

                SQLText = RemoveTail(SQLText, " AND (");
            }
            if (_orderBy.Count > 0)
            {
                SQLText += "ORDER BY " + String.Join(",", _orderBy);
            }

            SQLText = String.Format(SQLText, EntityAttribManager.Get<T>().Talbe.TableName);

            return SQLText;
        }
    }
}
